//
//  ComposeViewController.swift
//  SinaWebo
//
//  Created by mis on 16/3/23.
//  Copyright © 2016年 mis. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    private lazy var keyBoardView: EmoticonKeyBoardView = EmoticonKeyBoardView { [weak self] (em) -> () in
        self?.textView.insertEmoticon(em)
    }
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func send() {
        guard let token = UserAccountViewModel().access_token else {
            SVProgressHUD.showErrorWithStatus("哇咔咔，你还没有登录哟")
            return
        }
        let paratemers = ["access_token": token,"status": textView.fullText()]
        if selectorVC.imageList.count > 0 {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let newImage = thumbnailImage(selectorVC.imageList[0], size: CGSize(width: 20, height: 20))
            
            let imageData = UIImageJPEGRepresentation(newImage, 0.05)!
            print("图片大小是\(imageData.length)")
            NetworkTools.sharedTools.uploadImage(urlString, parameters: paratemers, imageData: imageData, finished: { (result, error) -> () in
                if error != nil {
                    print("请求错误是\(error)")
                    SVProgressHUD.showErrorWithStatus(appErroTip)
                    return
                }
                SVProgressHUD.showInfoWithStatus("发布微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            })
        }else {
            let urlString = "2/statuses/update.json"
            NetworkTools.sharedTools.requestJsonDict(HTTPMethod.POST, urlString: urlString, parameters: paratemers) { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(appErroTip)
                    return
                }
                SVProgressHUD.showInfoWithStatus("发布微博成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        }
    }
    
    private func thumbnailImage(image: UIImage?, size: CGSize) -> UIImage {
        var newImge = UIImage()
        if image != nil {
            UIGraphicsBeginImageContext(size)
            image!.drawInRect(CGRect(x: 0, y: 0, width: size.width, height: size.height))
            newImge = image!
            UIGraphicsEndImageContext()
        }
        return newImge
    }
    
    @objc private func selectPicture() {
        selectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(224 + 80 + 40)
        }
    }
    
    @objc private func selectEmoticon() {
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil ? keyBoardView : nil)
        textView.becomeFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    private func setupUI() {
        setNavBar()
        setupTextView()
        setupToolBar()
        setSelectorView()
        registerNotification()
    }
    
    private func setSelectorView() {
        addChildViewController(selectorVC)
        view.addSubview(selectorVC.view)
        view.bringSubviewToFront(toolBar)
        selectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyboardWillChange(n: NSNotification) {
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let curv = n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        let offset = -screenH + rect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curv)!)
            self.view.layoutIfNeeded()
        }
    }
    
    private lazy var textView: EmoticonTextView = {
        let ev = EmoticonTextView()
        ev.delegate = self
        ev.font = UIFont.systemFontOfSize(18)
        ev.textColor = UIColor.lightGrayColor()
        ev.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        ev.alwaysBounceVertical = true
        return ev
    }()
    private lazy var placeHolderLabel: UILabel = UILabel(title: "分享新鲜事。。。", size: 18, color: UIColor.lightGrayColor())
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var selectorVC: PictureSelectorViewController = PictureSelectorViewController()
}

extension ComposeViewController: UITextViewDelegate {
    func textViewDidChangeSelection(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeViewController {
    
    private func setupToolBar() {
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            let spare = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(spare)
        }
        items.removeLast()
        toolBar.items = items
    }
    
    private func setupTextView() {
        view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(self.view)
            make.height.equalTo(self.view.bounds.height * 0.3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(4)
        }
    }
    
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        self.navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: UserAccountViewModel().name ?? "", size: 14, color: UIColor.lightGrayColor())
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}
